import json
from channels.generic.websocket import AsyncWebsocketConsumer
from channels.db import database_sync_to_async
from django.contrib.auth import get_user_model
from apps.orders.models import Order, DjChefOrder

User = get_user_model()

class OrderNotificationConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        user = self.scope['user']
        if user.is_authenticated:
            # 厨师加入自己的通知频道
            if hasattr(user, 'djchef'):
                self.chef_group_name = f'chef_{user.djchef.id}'
                await self.channel_layer.group_add(
                    self.chef_group_name,
                    self.channel_name
                )
            
            await self.accept()
        else:
            await self.close()

    async def disconnect(self, close_code):
        if hasattr(self, 'chef_group_name'):
            await self.channel_layer.group_discard(
                self.chef_group_name,
                self.channel_name
            )

    async def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message_type = text_data_json.get('type')
        
        if message_type == 'heartbeat':
            await self.send(text_data=json.dumps({
                'type': 'heartbeat',
                'message': 'pong'
            }))

    async def order_notification(self, event):
        # 发送订单通知给厨师
        await self.send(text_data=json.dumps({
            'type': 'order_notification',
            'order_id': event['order_id'],
            'message': event['message'],
            'status': event['status']
        }))

    async def status_update(self, event):
        # 发送状态更新通知
        await self.send(text_data=json.dumps({
            'type': 'status_update',
            'order_id': event['order_id'],
            'from_status': event['from_status'],
            'to_status': event['to_status'],
            'timestamp': event['timestamp']
        }))

    @database_sync_to_async
    def get_order_count(self, chef_id):
        return DjChefOrder.objects.filter(
            chef_id=chef_id,
            status='pending'
        ).count()